import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("贷款计算器");
        frame.setLayout(new FlowLayout());
        JLabel labelAmount = new JLabel("贷款本金");
        JLabel labelPeriod = new JLabel("期数");
        JLabel labelInterest = new JLabel("贷款年利率");
        JTextField txtAmount = new JTextField(10);
        JTextField txtPeriod = new JTextField(10);
        JTextField txtInterest = new JTextField(10);
        JRadioButton radioButton1 = new JRadioButton("等额本金");
        JRadioButton radioButton2 = new JRadioButton("等额本息");
        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(radioButton1);
        buttonGroup.add(radioButton2);
        JLabel labelTotalInt = new JLabel("总利息");
        JTextField txtTotalInt = new JTextField(20);
        JButton btn = new JButton("计算");
        frame.add(labelAmount);
        frame.add(txtAmount);
        frame.add(labelPeriod);
        frame.add(txtPeriod);
        frame.add(labelInterest);
        frame.add(txtInterest);
        frame.add(radioButton1);
        frame.add(radioButton2);
        frame.add(labelTotalInt);
        frame.add(txtTotalInt);
        frame.add(btn);

        ActionListener actionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String strMount = txtAmount.getText();
                int amount = Integer.parseInt(strMount);
                String strPeriod = txtPeriod.getText();
                int period = Integer.parseInt(strPeriod);
                String strInterest = txtInterest.getText();        //将txtInterest提取成字符串
                double interest = Double.parseDouble(strInterest); //将strInterest解析成double类型
                LoanCalculator loanCalculator = new LoanCalculator(amount,period,interest);
                Double result;
                if(radioButton1.isSelected()){
                    result = loanCalculator.calculateAvgInterest();
                }else{
                    result = loanCalculator.calculateAvgCap();
                }
                txtTotalInt.setText(result.toString());
            }
        };

        btn.addActionListener(actionListener);
        /*
        frame.add(labelAmount);
        frame.add(labelPeriod);
        frame.add(labelInterest);
        */
        frame.setVisible(true);
        frame.setSize(500,400);
    }
}